package com.mccken.mvcfamework.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: mccken-spring
 * @description: 简单实现Dispertservlet
 * @author: mccken
 * @create: 2020-05-17 23:44
 **/
public class SimpleDispatcerServlet extends HttpServlet {

	private Properties contextConfig = new Properties();

	private Map<String, Object> beanMap = new ConcurrentHashMap();

	private List<String> beanNameList = new ArrayList<>();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("-----调用doPost-----");
	}

	/**
	 * 开始初始化进程
	 * 1.定位
	 * 2.加载
	 * 3.注册
	 * 4.自动依赖注入
	 * 5.
	 *
	 * @param config
	 * @throws ServletException
	 */

	@Override
	public void init(ServletConfig config) throws ServletException {

		System.out.println("start");
		// 定位  
		doLoadConfig(config.getInitParameter("contextConfigLocation"));

		// 加载  
		doScanner();

		// 注册  
		doRegistry();

		// 自动依赖注入  
		doAutowired();

		// 如果是springMVC 会多设计一个HandlerMapping  
		// 将@RequestMapping中配置的 url 和一个Method关联上  
		// 以便于从浏览器获得用户输入的url以后，能够找到具体执行的method  
		initHandlerMapping();

	}

	private void initHandlerMapping() {

	}

	private void doAutowired() {
	}

	private void doRegistry() {

	}

	private void doScanner() {

	}

	private void doLoadConfig(String location) {

		// 在 spring 中是通过Reader去查找和定位的  

		// 这里直接通过 properties 获取  
		InputStream is = this.getClass().getClassLoader().getResourceAsStream(location.replace("classpath:", ""));

		try {
			contextConfig.load(is);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {

			try {
				if (null != is) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
